//
//  UserAccount.swift
//  SinaWeibo
//
//  Created by NeXTSTEP on 15/10/2.
//  Copyright © 2015年 NeXTSTEP. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding {
    var access_token: String?
    var expires_in: NSTimeInterval = 0{
        didSet{
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    var expires_date: NSDate?
    var uid: String?
    var name: String?
    var avatar_large: String?
    
    
    init(dict: [String: AnyObject]) {
        
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}

    
    
    func loadUserInfo(completion: (error: NSError?) -> ()){
        NetworkTools.sharedTools.loadUserInfo(uid!,access_token:access_token!) { (dict, error) -> () in
            if dict == nil || error != nil {
                print("你的网络不给力")
                //错误状态一定要返回  否则调用层不知道干嘛
                completion(error: error)
                return
            }
            
            self.name = dict!["name"] as? String
            self.avatar_large = dict!["avatar_large"] as? String
            self.saveUserAccount()
            completion(error: nil)
        }
    }
    
    //存取的地址
    static let accountPath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
    
    //从磁盘中获取缓存的自定义对象
    class  var shareUserAccount: UserAccount? {
        
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.accountPath) as? UserAccount {
            //判断是否过期
            if account.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return account
            }
        }
        
        return nil
    }
    
    
    
    //将用户信息保存到本地  使用归档
    func saveUserAccount(){
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
    }
    
    override var description: String {
        let properties = ["access_token","expires_in","uid","expires_date","name","avatar_large"]
        
        return "\(dictionaryWithValuesForKeys(properties))"
    }
    
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
    }

    
}
